package sg.nus.iss.vmcs.models;

import java.util.ArrayList;
import java.util.Comparator;

/**
 * Store Item class that holds a StoreObject and its quantity<br><br>
 * Modifications:
 * <li>Philip - Updated with observer pattern</li>
 * @author Olivio Miotto
 * @author Philip Chew
 */
public class StoreItem {

	private ArrayList<StoreItemObserver> observerList;
    private StoreObject	content;
    private int			quantity;

    public StoreItem(StoreObject content, int quantity) {
        this.content  = content;
        this.quantity = quantity;
        observerList  = new ArrayList<StoreItemObserver>();
    }

    /**
     * Returns store content
     * @return
     */
    public StoreObject getContent() {
        return content;
    }

    /**
     * Sets the store object
     * @param ct
     */
    public void setContent(StoreObject ct) {
    	content = ct;
    	notifyObservers();
    }

    /**
     * Sets the quantity of the StoreItem
     * @param quantity
     */
    public void setQuantity (int quantity) {
        this.quantity = quantity;
        notifyObservers();
    }

    /**
     * Gets the quantity of the Store
     * @return quantity
     */
    public int getQuantity () {
        return quantity;
    }

    /**
     * Stores an item
     */
    public void store () {
        quantity++;
        notifyObservers();
    }
    
    /**
     * Reduces the quantity
     */
    public boolean unstore() {
    	if(quantity > 0) {
    		quantity--;
    		notifyObservers();
    		return true;
    	}
    	else {
    		return false;
    	}
    }
    
    /**
     * Registers an observer
     * @param sio StoreItem Observer to register
     */
    public void registerObserver(StoreItemObserver sio) {
    	observerList.add(sio);
    }
    
    /**
     * Gets the comparator for store item
     * @return Comparator for store item
     */
    public static Comparator<StoreItem> getSIDscComparator() {
    	return new Comparator<StoreItem>() {
			@Override
			public int compare(StoreItem s1, StoreItem s2) {
				return new Integer(s2.getContent().getValue()).compareTo(new Integer(s1.getContent().getValue()));
			}
    	};
    }
    
    /**
     * Notifies all observers of this
     */
    private void notifyObservers() {
    	for(StoreItemObserver sio : observerList) {
    		sio.notifyChange(this.content.getName(), this.quantity, this.content.getValue());
    	}
    }
}

